import React from 'react';
import { Upload, Icon, message, Row, Col, Button, Carousel, Spin, Modal } from 'antd';
// import Swiper from 'swiper/dist/js/swiper.js'
// import 'swiper/dist/css/swiper.min.css';
import { connect } from 'dva';
import img from '../../../assets/head.png';
import { array } from 'prop-types';
import { UrlConfig } from "../../../services/fetch";

function getBase64(img, callback) {
    const reader = new FileReader();
    reader.addEventListener('load', () => callback(reader.result));
    reader.readAsDataURL(img);
}

function beforeUpload(file) {
    const isJPG = file.type === 'image/jpeg';
    const isPNG = file.type === 'image/png';
    if (!isJPG && !isPNG) {
        message.error('图片格式不正确');
    }
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isLt2M) {
        message.error('图片大小不能超过2M');
    }
    if (isJPG) {
        return isJPG && isLt2M;
    } else {
        return isPNG && isLt2M;
    }
}



@connect(({ add,comment }) => ({
    add: add,
    comment:comment
}))
export default class UploadDu extends React.Component {
    constructor() {
        super()
        this.changePage = null
    }
    state = {
        video_img: [],
        fileList: [],
        loading: false,
        current: 0,
        visible: false,
        contentImg: []
    };
    componentDidMount() {

        //订阅  从内容库选择
        window.PubSub.subscribe('getFromContent', this.getFromContent)
        
    }
    static getDerivedStateFromProps(nextProps, prevState) {
        if (nextProps.one === 1 && prevState.fileList.length > 1) {
            return { fileList: [] }
        }
        if (prevState.fileList.length <= 0) {
            //设置封面图初始化
            if (nextProps.isEdit.length > 0) {
                if (nextProps.isEdit.length === 1) {
                    return { fileList: [{ url: nextProps.isEdit[0] }] }
                } else {
                    let arr = []
                    nextProps.isEdit.map((item) => {
                        let obj = {
                            url: item
                        }
                        arr.push(obj)
                    })
                    return { fileList: arr }
                }
            } else {
                return { fileList: [] }
            }
        }
        return null
    }
    /**
     * 订阅发布   组件通信 从内容库选择
     */
    getFromContent = (data) => {
        let fileList = []
        if (data.type === 'biz_sobey_picture') {
            let img = data.keyFrameUrl
            if (this.props.one === 1) {
                fileList = [{
                    url: img
                }]
            } else {
                fileList = [...this.state.fileList]
                if (fileList.length === 3) {
                    fileList[Number(this.state.current)] = { url: img }
                } else {
                    fileList.push({ url: img })
                }
            }
            this.setState({
                fileList: fileList
            })
            let list = []
            fileList.map((item, index) => {
                list.push(item.url)
            })
            this.props.form.setFieldsValue({
                information_img: list.join()
            })
        }
    }
    /**
     * 上传改变
     */
    handleChange = (info) => {
        if (info.file.status === 'uploading') {
            this.setState({
                loading: true
            })
            return
        }
        if (info.file.status === 'done') {
            let fileList = {
                url: info.file.response.data
            }
            let fileListNew = []
            if (this.props.one === 2) {
                fileListNew = [...this.state.fileList]
                if (fileListNew.length === 3) {
                    fileListNew[Number(this.state.current)] = fileList
                } else {
                    fileListNew.push(fileList)
                }
            } else {
                fileListNew.push(fileList)
            }
            this.setState({
                fileList: fileListNew
            })
            let list = []
            fileListNew.map((item, index) => {
                list.push(item.url)
            })
            // console.log(list)
            // console.log(list.join())
            this.props.form.setFieldsValue({
                information_img: list.join()
            })
            this.setState({
                loading: false
            })
        }
    }

    /**
     * 从内容库选择
     */
    fromContent = () => {
        if (window.bar) {
            window.bar.show('picture', 'ggsc');//图片
            this.props.dispatch({ type: 'add/saveMchType', data: 'mchImg' })
        }
    }

    /**
     * 从正文选择OK
     */
    handleOk = () => {

    }

    /**
     * 从正文选择OK
     */
    imgClick = (data) => {
        let fileList = {
            url: data
        }
        let fileListNew = []
        if (this.props.one === 2) {
            fileListNew = [...this.state.fileList]
            if (fileListNew.length === 3) {
                fileListNew[Number(this.state.current)] = fileList
            } else {
                fileListNew.push(fileList)
            }
        } else {
            fileListNew.push(fileList)
        }
        this.setState({
            fileList: fileListNew,
            visible: false
        })
        let list = []
        fileListNew.map((item, index) => {

            if (item.url.substr(0, 7).toLowerCase() == "http://" || item.url.substr(0, 8).toLowerCase() == "https://") {
                item.url = item.url;
            } else {
                item.url = UrlConfig + item.url;
            }
            list.push(item.url)
        })
        this.props.form.setFieldsValue({
            information_img: list.join()
        })
    }
    /**
     * 从正文选择
     */
    getFromArtical = () => {

    }
    /**
     * 改變carouser
     */
    changePrev = () => {
        this.changePage.prev()
    }
    changeNext = () => {
        this.changePage.next()
    }
    /**
     * 从内容中选择
     */
    onContentSelect = () => {
        // console.log(this.props.add.activeKey);
        let activeKey = this.props.add.activeKey;
        if (activeKey == '1') {
            let ue = window.UE.getEditor('content');
            let html = ue.getContent();
            let data = [];
            //匹配图片（g表示匹配所有结果i表示区分大小写）
            var imgReg = /<img.*?(?:>|\/>)/gi;
            //匹配src属性
            var srcReg = /src=[\'\"]?([^\'\"]*)[\'\"]?/i;
            var arr = html.match(imgReg);
            if (!arr || arr.length == 0) {
                message.error('未从正文找到图片');
                return true;
            }
            for (let i = 0; i < arr.length; i++) {
                let src = arr[i].match(srcReg);
                //获取图片地址
                if (src[1]) {
                    data.push(src[1]);
                }
            }
            this.setState({
                visible: true,
                contentImg: data
            });
            // console.log(data);
        } else if (activeKey == '2') {
            let arr = this.props.add.uploadImageList;
            if (!arr || arr.length == 0) {
                message.error('未从正文找到图片');
                return true;
            }
            let data = [];
            for (let i = 0; i < arr.length; i++) {

                data.push(arr[i].img_path);

            }
            this.setState({
                visible: true,
                contentImg: data
            });
        }

    }

    fcUpload = ()=>{
        window.fc = new window.FcUpload({
            elem: 'fcUpload',
            oss: this.props.add.configJson.aliyunOssSwitch,       //是否为oss 上传
            multiple: false,  //是否允许上传多个文件
            type:'img', // 上传文件类型\ img 图片，  video 视频
            actionImg: `${UrlConfig}/fcpublic/uploads/uploadImg`,  //本地上传图片地址
            actionVideo:`${UrlConfig}/fcpublic/uploads/uploadVideo`,  //本地上传视频地址
            actionOss: this.props.add.configJson.actionOss,  //后端认证接口，获取临时上传凭证
            endpoint: this.props.add.configJson.endpoint,
            bucket: this.props.add.configJson.bucket,
            customDomain : this.props.add.configJson.customDomain,
            ossConfig: this.props.add.configJson,
            callback: (res) => {
                // console.log(res);
                let url;
                if(res.oss){  // oss 和本地返回数据结构不一样
                    url = res.response[0];
                }else{
                    url = res.response[0].data;
                }
                let fileList = {
                    url: url
                }
                let fileListNew = []
                if (this.props.one === 2) {
                    fileListNew = [...this.state.fileList]
                    if (fileListNew.length === 3) {
                        fileListNew[Number(this.state.current)] = fileList
                    } else {
                        fileListNew.push(fileList)
                    }
                } else {
                    fileListNew.push(fileList)
                }
                this.setState({
                    fileList: fileListNew
                })
                let list = []
                fileListNew.map((item, index) => {
                    list.push(item.url)
                })
                this.props.form.setFieldsValue({
                    information_img: list.join()
                })
                this.setState({
                    loading: false
                })
            }
        });
        
        window.fc.show();
    }

    render() {
        const { fileList } = this.state;
        return (
            <div className='flex_box'>
                <Row gutter={24}>
                    <Col span={16}>
                        <Spin spinning={this.state.loading} >
                            <Carousel ref={e => this.changePage = e} afterChange={(current) => this.setState({ current })}>
                                {
                                    fileList.length > 0 ? fileList.map((item, index) => {
                                        return (
                                            <div key={index}>
                                                <img src={item.url ? item.url : img} width="100%" height="130px" alt="..." />
                                            </div>
                                        )
                                    }) : this.props.one === 2 ? (
                                        [1, 2, 3].map((item) => {
                                            return <div key={item}>
                                                <img src={img} width="100%" height="130px" alt="..." />
                                            </div>
                                        })
                                    ) : (
                                                <div>
                                                    <img src={img} width="100%" height="130px" alt="..." />
                                                </div>
                                            )
                                }
                            </Carousel>
                            {
                                this.props.one === 2 ?
                                    <div style={{ position: 'absolute', left: '0', top: '40%', fontSize: '20px', color: '#fff', cursor: 'pointer' }}
                                        onClick={this.changePrev}>
                                        <Icon type="left-circle" theme="outlined" />
                                    </div> : ''
                            }
                            {
                                this.props.one === 2 ?
                                    <div style={{ position: 'absolute', right: '0', top: '40%', fontSize: '20px', color: '#fff', cursor: 'pointer' }}
                                        onClick={this.changeNext}>
                                        <Icon type="right-circle" theme="outlined" />
                                    </div> : ''
                            }
                        </Spin>
                    </Col>

                    <Col className='pl_0' span={2} style={{ padding: '0 !important' }}>
                        <p className='mon_word' style={{ fontSize: '14px', color: '#afafaf', margin: '12px 0 0 0' }}>
                            ᠲᠠᠢᠯᠪᠤᠷᠢ᠄ ᠵᠢᠷᠤᠭ᠎ᠤᠨ ᠬᠡᠮᠵᠢᠶ᠎ᠡ᠎ᠨᠢ 2 M᠎ᠡᠴᠡ ᠬᠡᠲᠦᠷᠡᠵᠦ ᠪᠣᠯᠬᠤ᠎ᠦᠭᠡᠢ᠂ ᠬᠡᠯᠪᠡᠷᠢ᠎ᠨᠢ jpg/ png
                            {/* <br/>
                            建议上传图片尺寸比例为16:9，最小像素比为280*160 */}
                        </p>
                    </Col>
                    <Col span={2}>
                        <Button className='mon_text_btn' onClick={() => {
                            this.fcUpload();
                        }}>ᠳᠠᠮᠵᠢᠭᠤᠯᠬᠤ</Button>
                        {/* <Upload
                            action={`${UrlConfig}/fcinformation/Information/uploadImg`}
                            name="img"
                            showUploadList={false}
                            beforeUpload={beforeUpload}
                            onChange={this.handleChange}
                        >
                            <Button style={{ margin: '12px 0' }} >
                                上传
                        </Button>
                        </Upload> */}
                        {/* <Button style={{ margin: '0 10px' }} onClick={this.getFromArtical}>从正文</Button> */}
                        {this.props.add.configJson.mchSwitch ? <Button className='mon_text_btn' onClick={this.fromContent} >ᠠᠭᠤᠯᠭ᠎ᠠ᠎ᠶᠢᠨ ᠬᠥᠮᠥᠷᠭᠡ᠎ᠡᠴᠡ ᠰᠣᠩᠭᠣᠬᠤ</Button> : ''}
                        <Button className='mon_text_btn' onClick={this.onContentSelect}>ᠵᠣᠬᠢᠶᠠᠯ᠎ᠡᠴᠡ ᠰᠣᠩᠭᠣᠬᠤ</Button>
                        <Modal
                            title="从正文选择"
                            visible={this.state.visible}
                            width={530}
                            onOk={this.handleOk}
                            footer={null}
                            onCancel={() => {
                                this.setState({
                                    visible: false
                                })
                            }}
                        >
                            {this.state.contentImg.map((item) => {
                                return <img style={{ width: '100px', height: '100px', margin: '10px' }} src={item} onClick={() => { this.imgClick(item) }} />
                            })}
                        </Modal>
                    </Col>
                </Row>
                
                
            </div>
        );
    }
}
